package practice;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 案例：3个窗口抢100张票【lock锁】
 */
public class Practice3 {

    private static int ticket = 0;

    // 需要设置私有属性
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread("窗口1");
        MyThread myThread2 = new MyThread("窗口2");
        MyThread myThread3 = new MyThread("窗口3");

        myThread1.start();
        myThread2.start();
        myThread3.start();
    }


    private static class MyThread extends Thread {
        @Override
        public void run() {
            while (true) {
               try {
                   lock.lock();
                   if (ticket < 100) {
                       try {
                           Thread.sleep(10);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                       ticket++;
                       System.out.println(getName() + "正在抢票：" + ticket);
                   } else break;
               } catch (Exception e){
                   e.printStackTrace();
               } finally {
                   lock.unlock();
               }
            }
        }

        public MyThread(String name) {
            super(name);
        }
    }


}
